import React from 'react';
import {bindActionCreators} from 'redux';
import * as messageActionCreator from '../../actions/message-actions';
import {connect} from 'react-redux';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import {FlatList, Platform, StyleSheet, View} from 'react-native';
import {formatDate} from '../../utils';
import ThemeStyles from '../../styles';
import ListItem from '../../components/list-item';
import _ from 'lodash';
import {I18n} from '../../reducers/intl';

class NoticeScreen extends React.Component {
  static navigationOptions = () => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.sysmsg'),
  });

  componentDidMount() {
    const {messageActions} = this.props;
    messageActions.readSysMessage();
  }

  render() {
    const {systemMessages = {}, navigation} = this.props;
    const messages = Object.values(systemMessages).map(msg => ({
      ...msg,
      extra: formatDate(msg.created),
    }));
    return (
      <View style={Styles.container}>
        <FlatList
          data={_.orderBy(messages, 'created', 'desc')}
          renderItem={({item}) => (
            <ListItem
              label={item.title}
              extra={item.extra}
              onPress={() =>
                navigation.navigate('RichText', {item, title: item.title})
              }
            />
          )}
        />
      </View>
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  systemMessages: state.systemMessageList,
});

const mapDispatchToProps = dispatch => ({
  messageActions: bindActionCreators(messageActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(NoticeScreen));

const Styles = StyleSheet.create({
  container: {
    ...ThemeStyles.Color.background.white,
  },
});
